from odoo import api, models, fields, exceptions
from odoo.tools import date_utils
import re

class nbd_filemanager(models.Model):
    _name = 'nbd.filemanager'
    _description = 'NBD文件管理'
        
    @api.model
    def _default_task_id(self):
        if self.env.context.get('project_task_id'):
            return self.env.context.get('project_task_id') if self.env.context.get('project_task_id') else None
        return None
    
    @api.model
    def _default_stage_id(self):
        if self.env.context.get('task_stage'):
            return self.env.context.get('task_stage') if self.env.context.get('task_stage') else None
        return None
    
    project_task_id = fields.Many2one("project.task",string="Related Task", ondelete='cascade')

    name = fields.Char(string='文件名称')
    task_stage = fields.Char(string='所属阶段', default=_default_stage_id)
    task_moudle = fields.Char(string='所属模块')
    file_type = fields.Char(string='文件类型')
    DD_startTime = fields.Date(string='尽调开始时间')
    DD_endTime = fields.Date(string='尽调结束时间')
    group_members = fields.Char(string='调查小组成员')
    file_status = fields.Char(string='状态')

    
    contract_eflow_id = fields.Char(string='Eflow的合同编号')
    
    review_time = fields.Datetime(string='回顾时间')
    review_result = fields.Selection([
        ('1', "通过"),
        ('2', "未通过")
    ], string="回顾结果")
    
    task_file_ids = fields.One2many(
        comodel_name='ir.attachment',
        inverse_name='res_id',
        domain=lambda self: [('res_model', '=', self._name)],
        string='附件'
    )
    folder_id = fields.Many2one('nbd.folder', string='Folder')
    task_id = fields.Many2one(
        comodel_name='project.task',
        string='taskid',
    )
    @api.onchange('task_file_ids')
    def on_change_task_file_ids(self):
        for record in self:
            if record.task_file_ids:
                uploaded_file_count = len(record.task_file_ids)
                if uploaded_file_count > 1:
                    raise (exceptions.ValidationError("一条记录只能上传一个附件"))
                record.name = record.task_file_ids.name

    @api.constrains('task_file_ids')
    def _check_task_file_ids_length(self):
        for record in self:
            if record.task_file_ids:
                if len(record.task_file_ids) > 1:
                    raise (exceptions.ValidationError("一条记录只能上传一个附件,请删除对应附件后再次进行保存"))
    @api.depends('task_file_ids')
    def _compute_uploaded_file_count(self):
        for record in self:
            if record.task_file_ids:
                uploaded_file_count = len(record.task_file_ids)
                if uploaded_file_count > 1:
                    raise (exceptions.ValidationError("一条记录只能上传一个附件"))
                
    @api.constrains('contract_eflow_id')
    def _check_contract_eflow_id(self):
        for record in self:
            if record.contract_eflow_id:
                # 检查格式是否符合：“FMC20XXPCXXXX”
                pattern = r'^FMC20\d{2}PC\d{4}$'
                if not re.match(pattern,record.contract_eflow_id):
                    raise exceptions.ValidationError(("EFlow合同编号应符合以下规则：FMC20XXPCXXXX"))
                # 检查长度是否为18位
                if len(record.contract_eflow_id) != 13:
                    raise exceptions.ValidationError(("EFlow合同编号应为13位"))

    def create(self, vals_list):
        if self.env.context.get('project_task_id') and self.env.context.get('task_stage'):
            vals_list['task_id'] = self.env.context.get('project_task_id')
            vals_list['project_task_id'] = self.env.context.get('project_task_id')
            vals_list['task_stage'] = self.env.context.get('task_stage') if self.env.context.get('task_stage') else None
            nbd_folder = self.env['nbd.folder']
            folder = nbd_folder.search([
                # 定义查询条件，例如根据 my_field 字段的值
                ('task_id', '=', vals_list['task_id']),
                ('name', '=', vals_list['task_stage'])
            ])
            if folder:
                vals_list['folder_id'] = folder.id
            record = super().create(vals_list)
            return record
        else:
            for file_vals in vals_list:
                nbd_folder = self.env['nbd.folder']
                folder = nbd_folder.search([
                    # 定义查询条件，例如根据 my_field 字段的值
                    ('task_id', '=', file_vals['task_id']),
                    ('name', '=', file_vals['task_moudle'])
                ])
                if folder:
                    file_vals['folder_id'] = folder.id
                record = super().create(file_vals)

